﻿using System;
using System.Xml;
using System.Configuration;
using System.Collections.Generic;

namespace KKCai.Html
{
    public class ConfigurationSectionHandler : IConfigurationSectionHandler
    {
        public object Create(object parent, object configContext, XmlNode section)
        {
            return LoadValuesFromConfigurationFile(section);
        }

        private object LoadValuesFromConfigurationFile(XmlNode node)
        {
            List<Rule> rules = new List<Rule>();

            foreach (XmlNode n in node.ChildNodes)
            {
                if (n.NodeType == XmlNodeType.Comment)
                    continue;

                Rule rule = new Rule();

                XmlAttribute attribute = n.Attributes["url"];
                if (!(attribute == null || string.IsNullOrEmpty(attribute.Value)))
                    rule.LookFor = attribute.Value;
                
                attribute = n.Attributes["to"];
                if (!(attribute == null || string.IsNullOrEmpty(attribute.Value)))
                    rule.SendTo = attribute.Value;
                
                attribute = n.Attributes["min"];
                if (!(attribute == null || string.IsNullOrEmpty(attribute.Value)))
                    rule.TimeSpan = int.Parse(attribute.Value);

                rules.Add(rule);
            }

            return rules;
        }
    }
}
